package com.example.wangning.mycarofcountry.recommend.journalism;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.mycarofcountry.entity.dao.Recommend_News;
import com.example.wangning.mycarofcountry.R;
import com.example.wangning.mycarofcountry.cache.VolleySingleton;
import com.example.wangning.mycarofcountry.db.DaoHelper;
import com.example.wangning.mycarofcountry.listener.OnMyClickListener;
import com.example.wangning.mycarofcountry.tool.DividerGridItemDecoration;
import com.example.wangning.mycarofcountry.tool.DividerItemDecoration;
import com.example.wangning.mycarofcountry.tool.ShapeLoadingDialog;
import com.example.wangning.mycarofcountry.tool.ShapeLoadingView;
import com.example.wangning.mycarofcountry.webview.WebViewActivity;
import com.google.gson.Gson;

import java.io.DataInput;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 16/1/6.
 */
public class JournalismFragment extends Fragment {
    private RecyclerView recyclerView;
    private JournalismAdapter journalismAdapter;
    private VolleySingleton queue;
    private ShapeLoadingDialog dialog;
    private StringRequest stringRequest;
    private DaoHelper helper;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            dialog.show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    queue.addRequest(stringRequest);
                }
            }).start();

        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_journalism, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        journalismAdapter = new JournalismAdapter(getActivity());
        recyclerView.setAdapter(journalismAdapter);
        dialog = new ShapeLoadingDialog(getActivity());
        helper = DaoHelper.getInstance();
        initData();
    }

    private void initData() {
        queue = VolleySingleton.getVolleyIntance();
        String url = "http://api.budejie.com/api/api_open.php?market=taobao&order=timewarp&udid=359357052150266&a=list&appname=baisibudejie&c=data&os=4.3&client=android&userID=&page=1&per=20&sub_flag=1&visiting=&type=31&mac=50%3AFC%3A9F%3AFC%3A75%3A7E&maxtime=&ver=6.0.1";
        stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                dialog.dismiss();
                Gson gson = new Gson();
                JournalismBean journalismBean = gson.fromJson(response, JournalismBean.class);
                if (journalismBean != null) {
                    List<Recommend_News> resultEntity = journalismBean.getList();

                    if (resultEntity != null && resultEntity.size() > 0) {
                        journalismAdapter.addData(resultEntity);
                        helper.addNews(resultEntity);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                dialog.dismiss();
                journalismAdapter.addData(helper.seacherNews());
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
        };
        queue.addRequest(stringRequest);
    }


}
